package com.cskaoyan.proxy;

import com.cskaoyan.service.UserService;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 特定的组件生成代理对象
 * @author stone
 * @date 2021/11/19 14:45
 */
@Component
public class ServiceProxyFactoryBean implements FactoryBean {

    @Autowired
    @Qualifier("userServiceImpl")
    UserService userService;//委托类组件 👉 target

    @Override
    public Object getObject() throws Exception {
        Object proxy = Enhancer.create(userService.getClass(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("正道的光");
                Object invoke = method.invoke(userService, objects);
                System.out.println("照在大地上");
                return invoke;
            }
        });
        return proxy;
    }

    @Override
    public Class<?> getObjectType() {
        return userService.getClass();
    }
}
